import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/bezier_bounce_footer.dart';
import 'package:flutter_easyrefresh/bezier_circle_header.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hm_show_flutter/api/service/category_service.dart';
import 'package:hm_show_flutter/entity/category_list_entity.dart';
import 'package:hm_show_flutter/entity/goods.dart';
import 'package:hm_show_flutter/entity/goods_list_entity.dart';
import 'package:hm_show_flutter/style/style.dart';
import 'package:hm_show_flutter/utils/navigator_util.dart';
import 'package:hm_show_flutter/utils/toast_util.dart';
import 'package:hm_show_flutter/widgets/cached_image.dart';
import 'package:hm_show_flutter/widgets/empty_view.dart';
import 'package:hm_show_flutter/widgets/loading_dialog.dart';

///分类商品列表
class CategoryListPage extends StatefulWidget {
  final String categoryName;
  final int id;
  final int parentId;

  CategoryListPage(this.categoryName, this.id, this.parentId);

  @override
  _CategoryListPageState createState() => _CategoryListPageState();
}

class _CategoryListPageState extends State<CategoryListPage> {
  CategoryService _categoryService = new CategoryService();
  List<GoodsModel> _listCategory;

  bool isLoading;
  int _pageTotal; //总页数
  int _pageCurrent = 1; //当前页

  EasyRefreshController _controller = EasyRefreshController();

  @override
  void initState() {
    super.initState();
    getCategoryListData(false);
  }

  void getCategoryListData(bool isLoadMore) {
    if (isLoadMore) {
      //加载更多
      if (_pageCurrent >= _pageTotal) {
        ToastUtil.showToast("没有更多宝贝了~");
        _controller.finishLoad();
        return;
      }
      _pageCurrent++;
    } else {
      _pageCurrent = 1;
    }

    isLoading = true;
    _categoryService.getCategoryListData(_pageCurrent, widget.id,(success) {
      GoodsListEntity entity = success;
      try {

        setState(() {
          isLoading = false;
          _pageTotal = entity.data.pages;
          if (isLoadMore) {
            _controller.finishLoad();
            _listCategory.addAll(entity.data.xList);
          } else {
            _controller.finishRefresh();
            _listCategory = entity.data.xList;
          }
        });
        _controller.finishLoad();
      } catch (e, s) {
        print(s);
      }
    }, onFail: (fail) {
      if (isLoadMore) {
        _controller.finishLoad();
      } else {
        _controller.finishRefresh();
      }
      setState(() {
        isLoading = false;
      });
      _controller.finishLoad();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
          child: AppBar(
            iconTheme: IconThemeData(color: Colors.white),
            automaticallyImplyLeading: true,
            centerTitle: true,
            title: Text(
              widget.categoryName,
              style: TextStyle(color: Colors.white, fontSize: 16.0),
            ),
          ),
          preferredSize: Size.fromHeight(ScreenUtil.instance.height * 0.036)),
      body: _getContentView(),
    );
  }

  Widget _getContentView() {
    if (isLoading) {
      return LoadingDialog();
    } else if (_listCategory == null || _listCategory.isEmpty) {
      return EmptyView(
        onRetry: () {
          getCategoryListData(false);
        },
      );
    } else {
      return Container(
        child: EasyRefresh(
          controller: _controller,
          header: BezierCircleHeader(backgroundColor: AppColors.mainColor),
          footer: BezierBounceFooter(backgroundColor: AppColors.mainColor),
          enableControlFinishRefresh: true,
          enableControlFinishLoad: false,
          child: SingleChildScrollView(
            child: Container(
              padding: EdgeInsets.all(5.0),
              child: GridView.builder(
                  shrinkWrap: true,
                  itemCount: _listCategory.length,
                  physics: NeverScrollableScrollPhysics(),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2, childAspectRatio: 0.90),
                  itemBuilder: (BuildContext context, int index) {
                    return _getGridViewItem(context, _listCategory[index]);
                  }),
            ),
          ),
          onRefresh: () async {
            getCategoryListData(false);
          },
          onLoad: () async {
            getCategoryListData(true);
          },
        ),
      );
    }
  }

  Widget _getGridViewItem(BuildContext context, GoodsModel entity) {
    return Container(
      child: InkWell(
        onTap: (){
          NavigatorUtils.goGoodsDetailPage(context, entity.id);
        },
        child: Card(
          elevation: 2.0,
          child: Padding(
            padding: const EdgeInsets.all( 5),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Expanded(
                    child: CachedImageView(double.infinity,
                        ScreenUtil.instance.setHeight(80.0), entity.url)),
                Padding(
                  padding: EdgeInsets.only(top: 4.0),
                ),
                Container(
                  padding: EdgeInsets.only(left: 4.0, top: 4.0),
                  alignment: Alignment.center,
                  child: Text(
                    entity.name,
                    style: TextStyle(color: Colors.black54, fontSize: 14.0),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
